// 视频预览背景
import 'package:flutter/material.dart';
import 'package:zego_express_engine/zego_express_engine.dart';
import 'package:qgchat/http/models/TextureModel.dart';

class ZegoPreview extends StatefulWidget {
  final int screenWidthPx;
  final int screenHeightPx;

  ZegoPreview({
    @required this.screenWidthPx,
    @required this.screenHeightPx,
    Key key,
  }) : super(key: key);

  @override
  ZegoPreviewState createState() => ZegoPreviewState();
}

class ZegoPreviewState extends State<ZegoPreview> {
  TextureModel info;
  bool get isInit => info != null;
  bool isDispose = true;

  @override
  void initState() {
    super.initState();
    // 创建纹理渲染器
    ZegoExpressEngine.instance
        .createTextureRenderer(
      widget.screenWidthPx,
      widget.screenHeightPx,
    )
        .then((textureID) {
      // 创建一个纹理小部件
      final widget = Texture(textureId: textureID);
      // 设置预览画布 canvas
      final canvas = ZegoCanvas.view(textureID);

      info = TextureModel.fromJson({
        "textureID": textureID,
        "widget": widget,
        "canvas": canvas,
      });

      // 开始预览
      canvas.viewMode = ZegoViewMode.AspectFill;
      ZegoExpressEngine.instance.startPreview(canvas: info.canvas);
      setState(() {});
    });
  }

  @override
  void dispose() {
    // if (isDispose) {
      // 停止预览
      ZegoExpressEngine.instance.stopPreview();
      // 销毁预览组件
      ZegoExpressEngine.instance.destroyTextureRenderer(info.textureID);
    // }
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return isInit ? info.widget : Container();
  }
}

class ZegoPreviewBox extends StatelessWidget {
  const ZegoPreviewBox({Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Builder(
      builder: (context) {
        // 计算屏幕像素
        final width = MediaQuery.of(context).size.width.toInt();
        final height = MediaQuery.of(context).size.height.toInt();
        final ratio = MediaQuery.of(context).devicePixelRatio.toInt();
        final screenWidthPx = width * ratio;
        final screenHeightPx = height * ratio;
        return ZegoPreview(
          screenWidthPx: screenWidthPx,
          screenHeightPx: screenHeightPx,
        );
      },
    );
  }
}
